package com.gome.spiderkit.client;

import java.util.*;

import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.util.JSON;

public class CookieJar {
	
	private List<Cookie> _cookies;
	
	public CookieJar() {
		
	}

	public CookieJar(List<Cookie> cookies) {
		_cookies = cookies;
	}
	
	public Cookie get(String name) {
    	for (Cookie c : _cookies) {
    		if (c.name() == name)
    			return c;
    	}
    	return null;
    }
    
	public Cookie get(int index) {
    	if (index > _cookies.size())
    		return null;
    	
    	return _cookies.get(index);
    }

	public void set(String name, String value) {
		boolean hasCookie = false;
    	for (Cookie c : _cookies) {
    		if (c.name() == name) {
    			hasCookie = true;
    			c.setValue(value);
    		}
    	}
    	
    	if (!hasCookie) {
    		Cookie c = new Cookie();
    		c.setName(name);
    		c.setValue(value);
    		_cookies.add(c);
    	}
    }
    
	public  void set(Cookie cookie) {
		boolean hasCookie = false;
    	for (Cookie c : _cookies) {
    		if (c.name() == cookie.name()) {
    			hasCookie = true;
    			c.setValue(cookie.value());
    		}
    	}
    	if (!hasCookie)
    		_cookies.add(cookie);
    }

	public  int size() {
    	return _cookies.size();
    }
    
	public List<Cookie> cookies() {
    	return _cookies;
    }

	public boolean loadWithJson(String cookiesJson) {
		BasicDBList obj = (BasicDBList) JSON.parse(cookiesJson);
		if(obj == null)
			return false;
		for (int i = 0; i < obj.size(); i ++) {
			BasicDBObject cobj = (BasicDBObject) obj.get(i);
			Cookie c = new Cookie(cobj);
			_cookies.add(c);
		}
		return true;
    }

	public String toJson() {
		BasicDBList cs = new BasicDBList();
		for (Cookie c : _cookies)
			cs.add(c.content());
		return cs.toString();
    }
	
	public String toString() {
		String cookieHeader = "";
		for (Cookie c : _cookies)
			cookieHeader += c.name() + " : " + c.value() + ";";
		return cookieHeader;
    }
}
